import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService, urlService } from 'src/app/core/api';
import { CommonResponse, PageResponse, TradeOrderAndMerchantInfo, UserTransaction, UserWithdrawalCash, UserRecharge } from 'src/app/model';
import { environment } from 'src/environments/environment';
import { Billing } from '../model/billing';
import { BillingType } from '../model/type';

export type BillingDetail = TradeOrderAndMerchantInfo | UserTransaction | UserWithdrawalCash | UserRecharge;
export type BillingId = { withdrawalId: string } | { transactionId: string } | { tradeOrderId: string } | {id: string};

@Injectable()
export class BillingService {

  listBillings(data: {
    pageNo: number,
    startDate?: string,
    endDate?: string,
    type?: string,
    varId?:string
  }): Observable<PageResponse<Billing>> {
    return this.api.post<PageResponse<Billing>>(urlService(environment.type, '我的资产列表'), data);
  }

  getBillling(data: { type: BillingType; varId: string }): Observable<CommonResponse<BillingDetail>> {
    const key = this.getBillingUrlKey(data.type);
    const param = this.getBillingData(data.type, data.varId);
    return this.api.post<CommonResponse<BillingDetail>>(urlService(environment.type, key), param);
  }

  cancelWithdrawalCash(varId: string): Observable<CommonResponse<string>> {
    return this.api.post<CommonResponse<string>>(urlService(environment.type, '个人取消提现'), {
      withdrawalId: varId,
      status: 'CANCELED'
    });
  }

  error(error: any) {
    this.api.goToWhere(error);
  }

  constructor(
    private api: ApiService
  ) { }

  private getBillingUrlKey(bt: BillingType) {
    const map = new Map<string, string>();
    map.set('WITHDRAWAL_CASH', '个人提现详情页');
    map.set('WITHDRAWAL', '转账详情');
    map.set('DEPOSIT', '转账详情');
    map.set('TRADE_ORDER', '订单详情');
    map.set('RECHARGE', '充值记录详情');
    return map.get(bt.value);
  }

  private getBillingData(bt: BillingType, id: string) {
    const map = new Map<string, BillingId>();
    map.set('WITHDRAWAL_CASH', {
      withdrawalId: id
    });
    map.set('WITHDRAWAL', {
      transactionId: id
    });
    map.set('DEPOSIT', {
      transactionId: id
    });
    map.set('TRADE_ORDER', {
      tradeOrderId: id
    });
    map.set('RECHARGE', {
      id
    });
    return map.get(bt.value);
  }
}
